// pages/knowledge/knowledge.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    articles: [],
    filteredArticles: [],
    selectedCategory: 'all',
    searchQuery: '',
    categories: {
      'all': '全部',
      'nutrition': '营养饮食',
      'exercise': '运动健身',
      'disease': '疾病预防',
      'medication': '用药指南',
      'psychology': '心理健康'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 页面加载时获取健康知识数据
    this.loadArticles();
    
    // 如果URL传递了分类参数，则设置选中的分类
    if (options.category && this.data.categories[options.category]) {
      this.setData({
        selectedCategory: options.category
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 每次页面显示时刷新数据
    this.loadArticles();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  loadArticles: function() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 获取健康知识文章
    wx.request({
      url: 'http://localhost:3000/api/knowledge/articles',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const articles = res.data.data.articles || [];
          
          // 添加分类名称字段
          const articlesWithCategory = articles.map(article => {
            return {
              ...article,
              categoryName: this.data.categories[article.category] || '其他'
            };
          });
          
          this.setData({
            articles: articlesWithCategory,
            loading: false
          });
          
          // 应用筛选
          this.filterArticles();
        } else {
          console.error('获取健康知识文章失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取健康知识失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  filterArticles: function() {
    const { articles, selectedCategory, searchQuery } = this.data;
    
    let filtered = articles;
    
    // 应用分类筛选
    if (selectedCategory !== 'all') {
      filtered = filtered.filter(article => article.category === selectedCategory);
    }
    
    // 应用搜索筛选
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim();
      filtered = filtered.filter(article => 
        article.title.toLowerCase().includes(query) || 
        article.summary.toLowerCase().includes(query) || 
        article.content.toLowerCase().includes(query)
      );
    }
    
    this.setData({
      filteredArticles: filtered
    });
  },

  selectCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    
    this.setData({
      selectedCategory: category
    });
    
    // 更新筛选
    this.filterArticles();
  },

  onSearchInput: function(e) {
    const searchQuery = e.detail.value;
    
    this.setData({
      searchQuery: searchQuery
    });
    
    // 如果搜索关键词为空，显示所有文章
    if (!searchQuery.trim()) {
      this.setData({
        filteredArticles: this.data.articles
      });
      return;
    }
    
    // 在本地进行搜索过滤
    const filtered = this.data.articles.filter(article => {
      const searchLower = searchQuery.toLowerCase();
      return (
        article.title.toLowerCase().includes(searchLower) ||
        article.summary.toLowerCase().includes(searchLower) ||
        (article.content && article.content.toLowerCase().includes(searchLower))
      );
    });
    
    this.setData({
      filteredArticles: filtered
    });
  },

  clearSearch: function() {
    this.setData({
      searchQuery: '',
      filteredArticles: this.data.articles
    });
  },

  viewArticle: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/knowledge/detail/detail?id=${id}`
    });
  },

  onSearchFocus: function() {
    // 点击搜索框时清空内容
    this.setData({
      searchQuery: '',
      filteredArticles: this.data.articles
    });
  }
})